
//
//  EmoticonManager.swift
//  VVbo
//
//  Created by Mr.Run on 2017/9/7.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import Foundation

class EmoticonManager {
    static let shared = EmoticonManager()
    
    
    
    lazy var packages = [EmoticonPackage]()
    
    lazy var bundle: Bundle = {
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)
         return Bundle(path: path!)!
    }()
    
    private init(){
        loadPackages()
    }
    
    func recentEmoticon(em: Emoticon) {
        em.times += 1
        
        if !packages[0].emoticons.contains(em) {
            packages[0].emoticons.append(em)
        }
        
        packages[0].emoticons.sort { (em1, em2) -> Bool in
            return em1.times > em2.times
        }
        
        if packages[0].emoticons.count > 20 {
            packages[0].emoticons.removeSubrange(20..<packages[0].emoticons.count)
        }
        
    }
    
}

extension EmoticonManager {
    
    func emoticonString(string: String, font: UIFont) -> NSAttributedString {
        
        // AttributedString 是不可变的
        let attrString = NSMutableAttributedString(string: string)
        
        // 1. 建立正则表达式，过滤所有的表情文字
        // [] () 都是正则表达式的关键字，如果要参与匹配，需要转义
        let pattern = "\\[.*?\\]"
        
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
            return attrString
        }
        
        // 2. 匹配所有项
        let matches = regx.matches(in: string, options: [], range: NSRange(location: 0, length: attrString.length))
        
        // 3. 遍历所有匹配结果
        for m in matches.reversed() {
//            let rr = m.range(at: 0)
            let r = m.rangeAt(0)
            
            let subStr = (attrString.string as NSString).substring(with: r)
            
            // 1> 使用 subStr 查找对应的表情符号
            if let em = EmoticonManager.shared.findEmoticon(string: subStr) {
                
                // 2> 使用表情符号中的属性文本，替换原有的属性文本的内容
                attrString.replaceCharacters(in: r, with: em.imageText(font: font))
            }
        }
        
        // 4. *** 统一设置一遍字符串的属性，除了需要设置字体，还需要设置`颜色`！
        attrString.addAttributes([NSFontAttributeName: font,
                                  NSForegroundColorAttributeName: UIColor.darkGray],
                                 range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func findEmoticon(string: String) -> Emoticon? {
        for p in packages {
            let result = p.emoticons.filter({ (em) -> Bool in
                return em.chs == string
            })
            
            if result.count == 1 {
                return result[0]
            }
        }
        return nil
    }
    
}

extension EmoticonManager {
    
    func loadPackages() {
        guard  let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil),
            let bundle = Bundle(path: path),
            let plistPath = bundle.path(forResource: "emoticons.plist", ofType: nil),
            let array = NSArray(contentsOfFile: plistPath) as? [[String: String]],
            let models = NSArray.yy_modelArray(with: EmoticonPackage.self, json: array) as? [EmoticonPackage]
            else{
            return
        }
        
        packages += models
        
//        print(packages)
    }
    
}
